import React, { useEffect, useState } from 'react';
import { fetchTopics } from '../api';
import { useNavigate } from 'react-router-dom';

interface Topic {
  id: number;
  name: string;
  description: string;
  posts?: any[];
}

const TopicList: React.FC = () => {
  const [topics, setTopics] = useState<Topic[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    fetchTopics().then(res => {
      // 兼容后端返回格式 { data: topics, message: ... }
      let data = res.data;
      if (data && data.data) {
        setTopics(data.data);
      } else if (Array.isArray(data)) {
        setTopics(data);
      } else {
        setTopics([]);
      }
    });
  }, []);

  return (
    <div>
      <h2>话题列表</h2>
      <button onClick={() => navigate('/new-topic')}>发新帖</button>
      <ul>
        {Array.isArray(topics) && topics.map(topic => (
          <li key={topic.id} onClick={() => navigate(`/topics/${topic.id}`)}>
            {topic.name}（{topic.posts ? topic.posts.length : 0} 条动态）
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TopicList;